package com.gwtintegration.smartrf.builder;

import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.user.rebind.SourceWriter;

public class PrimitiveFieldConverterBuilder extends FieldConverterBuilder {

	protected PrimitiveFieldConverterBuilder(JMethod getterMethod, ProxyConverterBuilder proxyConverterBuilder) {
		super(getterMethod, proxyConverterBuilder);
	}

	@Override
	public boolean buildToProxy(SourceWriter sourceWriter) {

		if (!hasSetterMethod()) {
			return false;
		}

		JMethod setterMethod = getSetterMethod();
		JClassType parameterType = JMethodUtils.getSingleParameterType(setterMethod);
		JClassType valueType = parameterType.isClass();

		extractPrimitiveRecordAttribute(sourceWriter, getVariableName(), getAttributeName(), valueType);
		sourceWriter.println("proxy.%s(%s);", setterMethod.getName(), getVariableName());

		return true;
	}

	@Override
	public boolean buildToRecord(SourceWriter sourceWriter) {
		JMethod getterMethod = getGetterMethod();
		JClassType returnType = getterMethod.getReturnType().isClassOrInterface();

		sourceWriter.println("%s %s = proxy.%s();", returnType.getName(), getVariableName(), getterMethod.getName());
		sourceWriter.println("if(%s != null) {", getVariableName());
		sourceWriter.indent();
		sourceWriter.println("record.setAttribute(\"%s\", %s);", getAttributeName(), getVariableName());
		sourceWriter.outdent();
		sourceWriter.println("}");

		return true;
	}
}
